package toman.jpa;

import toman.TOQuery;

import javax.persistence.*;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: 21.4.11
 * Time: 14:42
 * To change this template use File | Settings | File Templates.
 */
public class JPAMain {

    public static void main(String[] args) throws Exception {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("album");
        EntityManager entityManager = entityManagerFactory.createEntityManager();

        JPATOMan toMan = new JPATOMan(entityManager);

        SimplePhotoWithAlbumAndAuthor simplePhotoWithAlbumAndAuthor = toMan.findTO(SimplePhotoWithAlbumAndAuthor.class, 351);
        System.out.println(simplePhotoWithAlbumAndAuthor);

        SimplePhotoTO simplePhoto = toMan.findTO(SimplePhotoTO.class, 351);
        System.out.println(simplePhoto);

        BasicPhotoAlbumWithDateTO photoWithOthers = toMan.findTO(BasicPhotoAlbumWithDateTO.class, 351);
        System.out.println(photoWithOthers);


        BasicAlbumWithBasicPhotosTO albumTOWithPhotoTOs = toMan.findTO(BasicAlbumWithBasicPhotosTO.class, "a1");
        System.out.println(albumTOWithPhotoTOs.getAlbumName());
        System.out.println(albumTOWithPhotoTOs.getPhotoTOs());


        BasicAlbumWithPhotosTO albumWithPhotos = toMan.findTO(BasicAlbumWithPhotosTO.class, "a1");
        System.out.println(albumWithPhotos.getAlbumName());
        System.out.println(albumWithPhotos.getPhotos());

        // List all photos
        TOQuery<BasicPhotoAlbumTO> query = toMan.createQuery(BasicPhotoAlbumTO.class, null);
        List<BasicPhotoAlbumTO> results = query.getResults();
        for (BasicPhotoAlbumTO to : results) {
            System.out.println(to.getPhotoId() + " " + to.getPhotoDescription() + " " + to.getAlbumName());
        }

        EntityTransaction tx = entityManager.getTransaction();
        tx.begin();

        // finding the photo for a given ID
        BasicPhotoAlbumTO to = toMan.findTO(BasicPhotoAlbumTO.class, 351);
        to.setPhotoDescription(to.getPhotoDescription() + "!");
        // updating the photo's description
        toMan.updateTO(to);

        tx.commit();

    }
}
